<?php

namespace pc\controllers;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

class BaseController extends Controller
{
    /**
     * @desc 公共分页 不要问我为什么这里的会这样 我不会告诉你这是我很多很多年前写的 ………… 那是一个很久很久以前的故事……………………end
     * @param array $pagination
     * @return string
     */
    public function createPageString($pagination = []){
        $pageIndex = intval($pagination['currentPage']);
        $pageSize = intval($pagination['perPage']);
        $totalCount = intval($pagination['totalCount']);

        $url = trim($pagination['formatUrl']);
        $first = trim($pagination['firstUrl']);
        $result = '';
        if ($pageSize < $totalCount) {
            $pages = ceil($totalCount / $pageSize);

            //确定上一页
            if ($pageIndex == 1) {
                $_url = $url;
                $_url = str_replace("{page}", $pages, $_url);
                $result = '<a class="pre" href=' . $_url . '><i></i></a>';
            } else if ($pageIndex > 1) {
                $_url = $url;
                $_url = str_replace("{page}", $pageIndex - 1, $_url);
                if ($pageIndex - 1 == 1) {
                    $_url = $first;
                }
                $result = '<a  class="pre" href=' . $_url . '><i></i></a>';
            }
            $start = 1;
            $end = 1;
            if ($pages < 11) {
                //正常输出10个page
                $end = $pages;
            } else if ($pages >= 11) {

                if ($pageIndex < 6) {
                    //正常输出前10个
                    $end = 10;
                } else if ($pageIndex <= $pages - 5) {
                    //输入前后各5个
                    $start = $pageIndex - 5;
                    $end = $pageIndex + 4;
                } else {
                    //向后推移，正常显示最后面10个
                    $start = $pages - 9;
                    $end = $pages;
                }
            }
            for ($start; $start <= $end; $start++) {
                $_url = $url;
                $_url = str_replace("{page}", $start, $_url);
                $_sel = '';
                if ($pageIndex == $start) {
                    $_sel = "class='cur'";
                }
                if ($start == 1) {
                    $_url = $first;
                }
                $result .= '<a ' . $_sel . ' href="' . $_url . '">' . $start . '</a>';
            }


            //确定下一页
            if ($pageIndex == $pages) {
                $_url = $url;
                $_url = str_replace("{page}", 1, $_url);
                $result .= '<a class="next" href=' . $first . '><i></i></a>';
            } else if ($pageIndex < $pages) {
                $_url = $url;
                $_url = str_replace("{page}", $pageIndex + 1, $_url);
                $result .= '<a class="next" href=' . $_url . '><i></i></a>';
            }

        }
        return $result;


    }

    public function noFound(){
        throw new NotFoundHttpException(404);
    }
}
